package com.example.messagedemo.config;


import com.example.messagedemo.common.CommonSendStatus;
import com.example.messagedemo.config.filter.WebsocketFilter;
import com.example.messagedemo.websocket.SocketHandler;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * web套接字配置
 *
 * @author dlp
 * @date 2024/08/22
 */
@Configuration
@EnableWebSocket
public class WebSocketConfiguration {

    /**
     * 	注入ServerEndpointExporter，
     * 	这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

    @Bean
    public WebsocketFilter websocketFilter(){
        return new WebsocketFilter();
    }



    @Bean
    public FilterRegistrationBean getFilterRegistrationBean(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(websocketFilter());
        // 临时注释掉，测试下线上socket总断的问题
        bean.addUrlPatterns("/taskCountSocket/*", "/websocket/*","/eoaSocket/*","/eoaNewChatSocket/*", "/newsWebsocket/*", "/vxeSocket/*");
        return bean;
    }

    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                            MessageListenerAdapter messageListenerAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        // 设置订阅的频道名
        container.addMessageListener(messageListenerAdapter, new ChannelTopic(CommonSendStatus.REDIS_TOPIC_NAME));
        return container;
    }


    @Bean
    MessageListenerAdapter messageListenerAdapter(SocketHandler socketHandler) {
        return new MessageListenerAdapter(socketHandler);
    }



}
